import sys
from Jlink import Ui_MainWindow
from PyQt5 import QtWidgets, QtGui
from PyQt5.QtCore import pyqtSignal, QThread
from PyQt5.QtWidgets import QFileDialog
import JlinkProgram
import time
import threading


# 烧录回调函数，用于获取当前操作的动作和百分比,暂时没用到它
def progress(action, progress_string, percentage):
    print(percentage)


class MyWindow(QtWidgets.QMainWindow, Ui_MainWindow):
    def __init__(self):
        super(MyWindow, self).__init__()
        self.setupUi(self)
        self.jlk = JlinkProgram.JLinkProgram()
        # 获取通过USB连接的J-Link列表序列号
        serial_list = self.jlk.get_jlkserialnum()
        for item in serial_list:
            self.comboBox_jlinkserialnum.addItem(item)

    def pushButton_datafile_click(self):
        print('datafileButton clicked')
        openfile_name, _ = QFileDialog.getOpenFileName(self, '选择镜像', '', '(*.hex , *.bin)')
        self.lineEdit_datafile.setText(openfile_name)

    def pushButton_connect_click(self):
        jlkserialnum = self.comboBox_jlinkserialnum.currentText()
        device = self.comboBox_device.currentText()
        interface = self.comboBox_interface.currentText()
        speed = self.comboBox_speed.currentText()
        self.threadConnect = ThreadAsync(self.jlk.jlk_connect, jlkserialnum, device, interface, speed)
        self.threadConnect.taskFinished.connect(self.on_btnConnect_finished)
        self.threadConnect.start()

    def on_btnConnect_finished(self):
        if self.pushButton_connect.text() == "Connect":
            local_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
            self.textBrowser_log.append(local_time + ": " + "Jlink connect")
            # 连接成功后，使能其他按键
            self.pushButton_erase.setEnabled(True)
            self.pushButton_read.setEnabled(True)
            self.pushButton_program.setEnabled(True)
            # 将连接按键失能
            self.pushButton_connect.setEnabled(False)

            mcuinfo = self.jlk.GetMcuInfo()
            self.lineEdit_ARM_id.setText(str(mcuinfo[0]))
            self.lineEdit_CPU_id.setText(str(mcuinfo[1]))
            self.lineEdit_Core_name.setText(mcuinfo[2])
            self.lineEdit_Device_family.setText(str(mcuinfo[3]))

    def pushButton_erase_click(self):
        self.threadErase = ThreadAsync(self.jlk.jlk_erase)
        self.threadErase.taskFinished.connect(self.on_btnErase_finished)
        self.threadErase.start()

    def on_btnErase_finished(self):
        local_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        self.textBrowser_log.append(local_time + ": " + "Erase finish")

    def pushButton_read_click(self):
        print("to be done...")
        addr_str = self.lineEdit_progaddr.text()
        # 用int函数将16进制字符串转化为10进制整数
        addr_int = int(addr_str, 16)
        if self.comboBox_device.currentText() == "STM32F103C8":
            size = 0x10000
        self.threadRead = MyThread(self.jlk.jlk_read, (addr_int, size))
        self.threadRead.start()
        print(self.threadRead.get_result())
        self.sm = QtGui.QStandardItemModel()
        self.sm.setHorizontalHeaderLabels(['Address', '0', '1', '2', '3', '4', '5', '6', '7', '8',
                                           '9', 'A', 'B', 'C', 'D', 'E', 'F', 'ASCII'])
        for i in range(addr_int, addr_int+size, 16):
            index_value = (i - addr_int)//16
            item_value = hex(i)
            item_value_str = str(item_value)
            # print(index_value)
            # print(type(item_value_str))
            self.sm.setItem(index_value, 0, QtGui.QStandardItem(item_value_str))

        # 隐藏默认的行号
        header = self.tableView_device_memory.verticalHeader()
        header.hide()
        # 将数据模型绑定到QTableView
        self.tableView_device_memory.setModel(self.sm)

    def pushButton_program_click(self):
        datafile_name = self.lineEdit_datafile.text()
        file_type = datafile_name.split('.')[-1]
        if file_type == "hex":
            addr = 0
        else:
            addr = self.lineEdit_progaddr.text()
        self.threadProgram = ThreadAsync(self.jlk.write_flash, datafile_name, addr, progress)
        self.threadProgram.taskFinished.connect(self.on_btnProgram_finished)
        self.threadProgram.start()

    def on_btnProgram_finished(self):
        local_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
        self.textBrowser_log.append(local_time + ": " + "Program OK finish")


class ThreadAsync(QThread):
    taskFinished = pyqtSignal()

    def __init__(self, func, *args):
        super(ThreadAsync, self).__init__()
        self.func = func
        self.args = args

    def run(self):
        self.result = self.func(*self.args)
        self.taskFinished.emit()


class MyThread(threading.Thread):
    def __init__(self, func, args=()):
        super(MyThread, self).__init__()
        self.func = func
        self.args = args

    def run(self):
        self.result = self.func(*self.args)

    def get_result(self):
        threading.Thread.join(self)  # 等待线程执行完毕
        return self.result


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    myshow = MyWindow()
    myshow.show()
    sys.exit(app.exec_())
